package org.rslai.tcedit.dao.hibernate;

import java.util.List;
import org.rslai.tcedit.dao.RoleDao;
import org.rslai.tcedit.domain.Page;
import org.rslai.tcedit.domain.Role;
import org.rslai.tcedit.exception.ApplicationException;

/***
 * RoleDao 的实现类
 * @author rslai
 *
 * @spring.bean id="roleDao"
 */
public class RoleDaoImpl extends GenericHibernateDao<Role> implements RoleDao {

	public RoleDaoImpl() {
		super(Role.class);
	}

	/**
	 * 创建一个 Role 信息。覆盖 GenericHibernateDao 中的 create 方法。
	 * 
	 * @param role Role对象
	 */
	public void create(Role role) {
		Role tmpRole = (Role) queryForObject(
				"from Role as a where a.name=?",
				new Object[] { role.getName() }
		);
		if (tmpRole != null) {
			throw new ApplicationException("您输入的“角色名称”已存在，请重新输入。");
		}

		hibernateTemplate.save(role);
	}

	private static final String QUERY_ROLE_ASC = "from Role as a order by a.name";
	private static final String QUERY_ROLE_DESC = "from Role as a order by a.name desc";

	@SuppressWarnings("unchecked")
	public List<Role> query(boolean asc) {
		return queryForList(
				asc ? QUERY_ROLE_ASC : QUERY_ROLE_DESC,
				null);
	}

	private static final String QUERY_ROLE_NAME_ASC = "from Role as a where a.name LIKE ? order by a.name";
	private static final String QUERY_ROLE_NAME_DESC = "from Role as a where a.name LIKE ? order by a.name desc";

	@SuppressWarnings("unchecked")
	public List<Role> query(Page page, String name, boolean asc) {
		return queryForList(
				"select count(*) from Role as a where a.name LIKE ?",
				asc ? QUERY_ROLE_NAME_ASC : QUERY_ROLE_NAME_DESC,
				new Object[] { name },
				page);
	}

	private static final String QUERY_BONDING = "from Role as a where a.bonding=true order by a.name";
	private static final String QUERY_NOT_BONDING = "from Role as a where a.bonding=false order by a.name";

	@SuppressWarnings("unchecked")
	public List<Role> queryBonding(boolean bonding) {
		return queryForList(
				bonding ? QUERY_BONDING : QUERY_NOT_BONDING,
				null);
	}

}